/**
 * 设置店铺弹框
 */
import { useState, useEffect, useMemo, useRef } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import CommonTable from '@/components/CommonTable';
import CommonPagination from '@/components/CommonPagination';
import { Form, Button, Select, Input, Popconfirm, message, Empty } from 'antd';
import { getShopList } from '@/services/common';
import { SearchOutlined, RightOutlined, EditOutlined, CheckOutlined, CloseOutlined, DeleteOutlined, DownOutlined } from '@ant-design/icons';
import { platformTypeName } from '@/utils/config';
import DragList from '@/components/DragList';
import { remove, find, cloneDeep } from 'lodash';
import api from './service.js';
import styles from './index.module.less';

const { Option } = Select;

export default (props) => {

	const { visible, handleOk, handleCancel } = props;

	const [loading, setLoading] = useState(false);

	const [form] = Form.useForm();

	const inputRef = useRef(null);

	const [searchStr, setSearchStr] = useState();

	//分组列表
	const [groupList, setGroupList] = useState([]);

	//门店列表
	const [storeList, setStoreList] = useState([]);

	//设置分组开启关闭
	const [openGroup, setOpenGroup] = useState({});

	const [pages, setPages] = useState({
		current: 1,
		pageSize: 20,
		total: 0
	})

	//当前选中的门店
	const [selectRowKeys, setSelectRowKeys] = useState([]);

	//当前编辑的组信息
	const [editIem, setEditItem] = useState({});

	//新建分组计数id
	const [id, setId] = useState(0);

	//当前激活的组，用于店铺设置
	const [current, setCurrent] = useState({});

	useEffect(() => {
		getGroupList();
	}, [])

	useEffect(() => {
		getStoreList();
	}, [pages.current, pages.pageSize])

	//获取分组列表
	const getGroupList = async () => {
		const { success, data } = await api.queryShopGroups();
		if (success) {
			data.ecStoreSearchGroupList.map(v => {
				v.customId = 'origin' + v.id;
			})
			setGroupList(data.ecStoreSearchGroupList);
		}
	}

	//获取店铺列表
	const getStoreList = async () => {
		const formData = form.getFieldsValue();
		const params = {
			...formData,
			current: pages.current,
			size: pages.pageSize
		}
		setLoading(true);
		const { success, data } = await getShopList(params);
		setLoading(false);
		if (success) {
			setStoreList(data.records);
			setSelectRowKeys([]);
			setPages({
				...pages,
				total: data.total
			})
		}
	}

	//左侧组操作事件
	//添加组
	const addGroup = () => {
		if (searchStr) {
			message.info('添加组之前请先清空搜索条件！');
			return;
		}
		const obj = {
			customId: 'custom' + id,
			groupName: id > 0 ? `新建分组${id}` : '新建分组',
			ecStoreSearchDetailList: [],
		}
		const arr = [...groupList, obj];
		const editItem = {
			editName: obj.groupName,
			editId: obj.customId
		}
		setId(id + 1);
		setGroupList(arr);
		setEditItem(editItem);
	}

	//每次添加组之后聚焦当前输入框
	useEffect(() => {
		inputRef.current && inputRef.current.focus();
	}, [editIem.editId])

	//点击组
	const clickGroup = val => {
		if (current.customId && current.customId == val.customId) {
			return;
		}
		setCurrent(val);
	}

	//编辑组
	const editGroup = val => {
		setEditItem({
			editId: val.customId,
			editName: val.groupName
		})
	}

	//删除组
	const delGroup = val => {
		const arr = [...groupList];
		remove(arr, ['customId', val.customId]);
		if (val.customId == current.customId) {
			setCurrent({});
		}
		setGroupList(arr);
	}

	//保存组
	const saveGroup = () => {
		if (!editIem.editName.trim()) {
			message.info('请输入组名');
			return;
		}
		const obj = find(groupList, ['customId', editIem.editId]);
		obj.groupName = editIem.editName;
		setEditItem({});
	}

	//批量添加店铺
	const batchAddStore = () => {
		if (selectRowKeys.length == 0) {
			message.info('请先选择要添加的店铺');
			return;
		}
		const arr = [];
		for (let i in selectRowKeys) {
			const obj = find(storeList, ['id', selectRowKeys[i]]);
			if (obj) {
				arr.push({
					ecStoreId: obj.id,
					type: obj.type,
					storeName: obj.storeName
				});
			}
		}
		current.ecStoreSearchDetailList = [...current.ecStoreSearchDetailList, ...arr];
		setSelectRowKeys([]);
	}

	//单个添加店铺
	const addStore = val => {
		const arr = cloneDeep(groupList);
		const obj = find(arr, ['customId', current.customId]);
		obj.ecStoreSearchDetailList.push(val);
		const list = [...selectRowKeys];
		if (list.includes(val.ecStoreId)) {
			remove(list, v => v == val.ecStoreId)
		}
		setSelectRowKeys(list);
		setCurrent(obj);
		setGroupList(arr);
	}

	//删除店铺
	const delStore = (ecStoreId, customId) => {
		const arr = cloneDeep(groupList);
		const obj = find(arr, ['customId', customId]);
		if (obj) {
			remove(obj.ecStoreSearchDetailList, ['ecStoreId', ecStoreId]);
		}
		if (customId == current.customId) {
			setCurrent(obj);
		}
		setGroupList(arr);
	}

	//拖拽店铺
	const dragEnd = (val, v) => {
		const arr = cloneDeep(groupList);
		const obj = find(arr, ['customId', v.customId]);
		if (obj) {
			obj.ecStoreSearchDetailList = val;
		}
		setGroupList(arr);
	}

	//点击查询
	const onFinish = () => {
		getStoreList();
	}

	//点击重置
	const onReset = (e) => {
		form.resetFields();
		getStoreList();
	}

	//点击确定
	const onOk = async () => {
		setLoading(true);
		const { success } = await api.updateShopGroups(groupList)
		setLoading(false);
		if (success) {
			message.success('操作成功');
			handleOk();
		}
	}

	const onCancel = () => {
		handleCancel();
	}

	//当前正在激活的数据中存在店铺的id集合
	const currentData = current.ecStoreSearchDetailList?.map(v => v.ecStoreId) || [];

	//用于最终展示的数据
	const formatGroupData = useMemo(() => {
		if (searchStr) {
			const arr = [];
			for (let i in groupList) {
				if (groupList[i].ecStoreSearchDetailList.length > 0) {
					const list = groupList[i].ecStoreSearchDetailList;
					const obj = {
						...groupList[i],
						ecStoreSearchDetailList: []
					};
					for (let j in list) {
						if (list[j].storeName.includes(searchStr)) {
							obj.ecStoreSearchDetailList.push(list[j]);
						}
					}
					if (obj.ecStoreSearchDetailList.length > 0) {
						arr.push(obj);
					}
				}
			}
			return arr;
		} else {
			return groupList;
		}
	}, [groupList, searchStr])


	const columns = [
		{
			title: '平台',
			width: 120,
			dataIndex: 'typeName',
		},
		{
			title: '店铺名',
			width: 200,
			dataIndex: 'storeName',
		},
		{
			title: '操作',
			width: 80,
			dataIndex: 'name',
			render: (_, record) => {
				if (currentData.includes(record.id)) {
					return (
						<Button size='small' disabled>已添加</Button>
					)
				}
				return (
					<Button onClick={() => addStore({ ecStoreId: record.id, type: record.type, storeName: record.storeName })} size="small">添加</Button>
				)
			},
		},
	]


	const TableProps = {
		rowKey: 'id',
		size: 'small',
		data: storeList,
		scroll: {
			y: '40vh'
		},
		columns,
		rowSelection: {
			selectedRowKeys: selectRowKeys,
			onChange: (selectedRowKeys) => {
				setSelectRowKeys(selectedRowKeys);
			},
			getCheckboxProps: (record) => ({
				disabled: currentData.includes(record.id) ? true : false,
				// Column configuration not to be checked
			}),
		}
	}

	const pageProps = {
		pagination: pages,
		handleChange(current, size) {
			setPages({
				...pages,
				current: current == pages.current ? 1 : current,
				pageSize: size,
			});
		},
	};

	return (
		<CommonModal
			title="店铺筛选项分组"
			visible={visible}
			onCancel={onCancel}
			onOk={onOk}
			width="1000px"
		>
			<div className={styles.setWrap}>
				<div className={styles.setLeft}>
					<div className={styles.itemWrap}>
						<Input value={searchStr} onChange={e => setSearchStr(e.target.value)} placeholder="请输入店铺" style={{ width: '220px' }} prefix={<SearchOutlined />} />
						<span className={styles.addText} onClick={addGroup}>添加组</span>
					</div>
					{
						formatGroupData.map(v => {
							const isEdit = editIem.editId && editIem.editId == v.customId;
							const isOpen = openGroup[v.customId] == false ? false : true;
							//渲染拖拽节点
							const renderDragItem = (k) => (
								<div className={styles.storeItem}>
									<span>{k.storeName}【{platformTypeName[k.type]}】</span>
									<Popconfirm title="确定要将这个店铺从当前分组删除吗?" onConfirm={() => delStore(k.ecStoreId, v.customId)}>
										<DeleteOutlined className={styles.operaIcon} style={{ color: '#108ee9' }} />
									</Popconfirm>
								</div>
							)
							//渲染拖拽组件
							const DragListProps = {
								dragKey: 'ecStoreId',
								items: v.ecStoreSearchDetailList,
								renderDragItem,
								handleDragEnd(val) {
									dragEnd(val, v)
								}
							}
							return (
								<div className={styles.groupWrap} key={v.customId}>
									<div className={styles.groupItem}>
										{
											isOpen ?
												<DownOutlined onClick={() => setOpenGroup({ ...openGroup, [v.customId]: false })} className={styles.operaIcon} />
												:
												<RightOutlined onClick={() => setOpenGroup({ ...openGroup, [v.customId]: true })} className={styles.operaIcon} />
										}
										{
											isEdit ?
												<>
													<Input ref={inputRef} style={{ width: '160px', marginRight: '12px' }} maxLength={10} value={editIem.editName} onChange={e => setEditItem({ ...editIem, editName: e.target.value })} placeholder='请输入分组名' />
													<CheckOutlined onClick={saveGroup} className={styles.operaIcon} style={{ color: 'green' }} />
													<CloseOutlined onClick={() => setEditItem({})} className={styles.operaIcon} style={{ color: 'red' }} />
												</>
												:
												<>
													<span onClick={() => clickGroup(v)} style={{ marginRight: '12px', cursor: 'pointer', color: (current.customId && current.customId == v.customId) ? '#108ee9' : '#000' }}>{v.groupName}</span>
													<EditOutlined onClick={() => editGroup(v)} className={styles.operaIcon} style={{ color: '#108ee9' }} />
													<Popconfirm title="确定要删除该分组吗?" onConfirm={() => delGroup(v)}>
														<DeleteOutlined className={styles.operaIcon} style={{ color: '#108ee9' }} />
													</Popconfirm>
												</>
										}
									</div>
									{
										v.ecStoreSearchDetailList.length > 0 ?
											<div className={styles.storeWrap} style={{ display: isOpen ? 'block' : 'none' }}>
												<DragList {...DragListProps} />
											</div>
											:
											<div className={styles.storeWrap} style={{ display: isOpen ? 'block' : 'none' }}>
												<Empty imageStyle={{ height: '24px' }} description="暂无数据" />
											</div>
									}
								</div>
							)
						})
					}
				</div>
				<div className={styles.setRight}>
					{
						current.customId ?
							<>
								<Form
									form={form}
									name="shop=set-modal"
									layout="inline"
									onFinish={onFinish}
									className="search-form-style"
								>
									<Form.Item label="平台" name="typeGroup">
										<Select placeholder="请选择平台" allowClear>
											{
												Object.keys(platformTypeName).map(v => (
													<Option value={v} key={v}>{platformTypeName[v]}</Option>
												))
											}
										</Select>
									</Form.Item>
									<Form.Item label="店铺" name="storeName">
										<Input placeholder="请输入店铺" />
									</Form.Item>
									<Form.Item>
										<Button type="primary" htmlType="submit" style={{ margin: '0 8px 0 12px' }}>
											查询
										</Button>
										<Button onClick={onReset}>重置</Button>
									</Form.Item>
								</Form>
								<div style={{ margin: '12px 0' }}>
									<Button onClick={batchAddStore}>批量添加</Button>
								</div>
								<CommonTable {...TableProps} />
								<div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '12px' }}>
									<CommonPagination {...pageProps} />
								</div>
							</>
							:
							<Empty style={{ marginTop: '20vh' }} description="请先选择组" />
					}
				</div>
			</div>
			<CommonLoading loading={loading} />
		</CommonModal>
	)
}